//
//  NextViewController.m
//  dispatch_source
//
//  Created by 青梅睿创公司 on 2018/2/26.
//  Copyright © 2018年 青梅睿创公司. All rights reserved.
//

#import "NextViewController.h"

@interface NextViewController ()
{
    NSInteger time;
}
@property (nonatomic, strong) NSTimer * timer;

@end

@implementation NextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor redColor];
    
//    [self go];
    [self startTimer];
//    [self starTimerInChildThread];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)go{
    
    __block NSInteger time = 0;
    
    // 倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 每秒执行一次
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        if (time > 10) {
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"计时结束..");
                
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"---%lu", time);
            });
            
            time ++;
        }
        
        
    });
    
    dispatch_resume(_timer);
}

- (void)startTimer
{
    
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    // 添加到运行循环  NSRunLoopCommonModes:占位模式   主线程
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];  // 如果不改变Mode模式在滑动屏幕的时候定时器就不起作用了
    
}

- (void)starTimerInChildThread{
    [NSThread detachNewThreadSelector:@selector(bannerStart) toTarget:self withObject:nil];
}

// 在子线程中定义定时器
- (void)bannerStart{
    NSLog(@"。。。");
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (void)updateTimer{
    NSLog(@"%lu", time);
    time ++;
    if (time > 10) {
        [self.timer invalidate];
    }
}

- (void)dealloc{
    NSLog(@"Next被销毁了...");
}

@end
